/*
 * This file is part of LangMan.
 *
 * LangMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * LangMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LangMan.  If not, see <http://www.gnu.org/licenses/>.
 */

package langman.util.guifactory;

import langman.util.doping.Context;
import langman.util.doping.Inject;
import langman.util.doping.SingletonBean;

import java.io.IOException;

@SingletonBean
public class GUIFactory {
    private final BeanFXMLLoader loader;
    private final Context applicationContext;

    @Inject
    public GUIFactory(BeanFXMLLoader loader, Context applicationContext) {
        this.loader = loader;
        this.applicationContext = applicationContext;
    }

    public <T extends BeanControl> T createControl(Class<T> controllerClass) {
        T bean = FXMLBeanControl.class.isAssignableFrom(controllerClass) ?
                (T) loadSpringControl((Class<? extends FXMLBeanControl>) controllerClass) :
                loadNodeControl(controllerClass);

        if (!bean.hasBeenInitialized()) {
            bean.initializeControl();
        }

        return bean;
    }

    private <T extends BeanControl> T loadNodeControl(Class<T> controllerClass) {
        return applicationContext.getBean(controllerClass);
    }

    private FXMLBeanControl loadSpringControl(Class<? extends FXMLBeanControl> controllerClass) {
        try {
            String fxmlFileName = controllerClass.getSimpleName() + ".fxml";
            return loader.load(fxmlFileName, controllerClass);
        } catch (IOException e) {
            throw new ControlCreationException("Couldn't create control for " + controllerClass, e);
        }
    }
}
